define(["require",
        "dojo/_base/declare",
        "../BaseWidget",
        "dojo/text!./templates/Template.html",
        "dojo/_base/lang",
        "dojo/dom-style",
        "dojo/dom-construct",
        "dojo/on","dojo/topic",
        "dojo/_base/connect",
        "gistech/util/ajaxUtil",
        "esri/geometry/geodesicUtils",
        "esri/geometry/webMercatorUtils",
        "esri/tasks/QueryTask",
        "esri/tasks/query",
        "esri/toolbars/draw",
        "esri/layers/FeatureLayer","esri/InfoTemplate",
        "esri/symbols/PictureMarkerSymbol","esri/graphic",
        "esri/renderers/UniqueValueRenderer", "esri/Color",
        "esri/geometry/Polygon", "esri/geometry/Polyline","esri/symbols/SimpleLineSymbol",
        "esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleMarkerSymbol",
        "dojo/dom-style","dojo/query","dojo/dom-class"],
        function(require,declare,BaseWidget,template,lang,style,domConstruct,
        		on,topic,eventconnect,ajaxUtil,geodesicUtils,webMercatorUtils,QueryTask,Query,Draw,FeatureLayer,
        		InfoTemplate,PictureMarkerSymbol,Graphic,UniqueValueRenderer,Color,Polygon,Polyline,
        		SimpleLineSymbol,SimpleFillSymbol,SimpleMarkerSymbol,
        		domStyle,query,domClass){
	return declare([BaseWidget],{
		templateString:template,
		projectType:"WYTZ",
		moduleName:"外业拓展",
		LandFeatureLayer:null,
		landgeo:null,
		handles:[],
		landinfoTemplate:null,
		rightTab:null,
		addOrEdit:"addstate", 
		layerFieldsInfo:null,
		drawtool:null,
		currentDrawGraphic:null,
		addbuttons:null,
		editbuttons:null,
		resavebuttons:null,
		objectid:null,
		executeEditType:"add",
		symbol:null,
		feaSet:null,
		flyurl:null,
		constructor:function (args) {
			this.inherited(arguments);
			this.map = args.map;
			this.addOrEdit = args.addOrEdit;
			this.rightTab = args.rightTab;
			this.projectType = args.projectType;
			this.moduleName = args.moduleName;
			this.feaSet = args.feaset;
			this.flyurl = args.flyurl;
		},
		postCreate:function(){
			this.inherited(arguments);
			on(this.create, "click",lang.hitch(this,this.createLandBtnClickHandler));
			on(this.resave, "click",lang.hitch(this,this.resaveLandBtnClickHandler));
			on(this.deletebtn, "click",lang.hitch(this,this.deleteLandBtnClickHandler))
			on(this.getPoint,"click",lang.hitch(this,this.beginDrawPoint));
			on(this.closebtn,"click",lang.hitch(this,this.closeDialog));

			on(this.edit, "click",lang.hitch(this,this.editProjectInfo));

			on(this.leftarrow,"click",lang.hitch(this,this.panToProjectLocation));
		},
		startup:function(){
			this.inherited(arguments);    
			this.addEvents();
			this.init();
		},

		addEvents:function(){
			this.handles.push(topic.subscribe("windowResize", lang.hitch(this, this.windowResizeHandler)));
			this.handles.push(topic.subscribe("MapClickHandler",lang.hitch(this,this.listenerMapLandClickHandler)));
			//this.handles.push(topic.subscribe("ProjectManageWidgetOpen",lang.hitch(this,this.projectManageWidgetOpenHandler)));
		},
		init:function(){
			//topic.publish("ProjectManageWidgetOpen",this.projectType);

			if(this.feaSet){
				var feature = this.feaSet.features;
				this.objectId = feature.attributes["OBJECTID"];
				this.currentDrawGraphic = new Graphic(feature.geometry);
				this.projectName.innerText = feature.attributes["DKMC"]?feature.attributes["DKMC"]:(feature.attributes["XMMC"]?feature.attributes["XMMC"]:"");
			}

			this.addbuttons = dojo.query(".WYTZProjectManageWidget .addstate");
			this.editbuttons = dojo.query(".WYTZProjectManageWidget .editstate");
			this.resavebuttons = dojo.query(".WYTZProjectManageWidget .resavestate");
			this.symbol = new PictureMarkerSymbol(
					"gistech/widgets/PoiSearchWidget/images/lb2.png", 30, 30);
			this.symbol.setOffset(1, 13);
			this.modulenamespan.innerText = this.moduleName;

			this.windowResizeHandler();
			this.setTextType(this.addOrEdit);
			this.addLandsFeatureLayer();
		},

		panToProjectLocation:function(){

			if(this.feaSet==null){
				topic.publish("isHadLoadLayerEvent",mapinfoTemplate[this.projectType].layerDisplayName);
			}

			var obj = this.currentDrawGraphic;
			var geo = obj.geometry;
			var symbol = null;
			var ext = null;
			if (obj.geometry.type == "point") {
				symbol = new PictureMarkerSymbol(
						"gistech/widgets/PoiSearchWidget/images/lb1.png", 30, 30);
				symbol.setOffset(1, 13);
				
				var x_max = geo.x + 4000 / 2;
				var x_min = geo.x - 4000 / 2;
				var y_max = geo.y + 2000 / 2;
				var y_min = geo.y - 2000 / 2;
				ext = new esri.geometry.Extent(x_min, y_min, x_max, y_max, this.map.spatialReference);
				
			} else if (obj.geometry.type == "polygon") {
				symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
						new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT, new Color([255, 0, 0 ]), 2), new Color([ 255, 255, 0, 0.25 ]));
				ext = geo.getExtent();
			} else if (obj.geometry.type == "polyline") {
				symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new Color([255, 0, 0 ]), 4);
				ext = geo.getExtent();
			}
			this.map.setExtent(ext);
			var graphic = new Graphic(geo, symbol, obj);

			this.map.graphics.clear();
			this.map.graphics.add(graphic); //用默认的图层添加点对象
			this.refreshGraphic(graphic, symbol);
		},
		refreshGraphic : function(geo, symbol) {
			geoType = geo.geometry.type;
			var resizeInterval1, resizeInterval2;
			var resizeTimer, resizeTime = 2000;
			clearTimeout(resizeTimer);

			resizeInterval1 = setInterval(function() {
				var symbol = null;
				if (geoType.toLowerCase() == 'polygon') {
					symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
							new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT, new Color([
							                                                                0, 255, 255 ]), 2), new Color([ 0, 255, 255, 0.25 ]));
				} else if (geoType.toLowerCase() == 'polyline') {
					symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID,
							new Color([ 0, 255, 255, 1 ]), 3);
				} else if (geoType.toLowerCase() == 'point') {
					symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10,
							new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([ 0,
							                                                               255, 255 ]), 1), new Color([ 0, 255, 255, 0.25 ]));
				}
				geo.setSymbol(symbol);
			}, 200);
			resizeInterval2 = setInterval(function() {
				var symbol = null;
				if (geoType.toLowerCase() == 'polygon') {
					symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID,
							new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASHDOT, new Color([
							                                                                255, 0, 0 ]), 2), new Color([ 255, 255, 0, 0.25 ]));
				} else if (geoType.toLowerCase() == 'polyline') {
					symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_DASH, new Color(
							[ 255, 0, 0 ]), 4);
				} else if (geoType.toLowerCase() == 'point') {
					symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10,
							new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([
							                                                              255, 0, 0 ]), 1), new Color([ 255, 0, 0, 0.25 ]));
				}
				geo.setSymbol(symbol);
			}, 220);

			resizeTimer = setTimeout(function() {
				clearInterval(resizeInterval1);
				clearInterval(resizeInterval2);
				geo.setSymbol(symbol);// 还原图像样式
			}, resizeTime);

			geo.setSymbol(symbol);// 解决颜色因为延迟问题不一致
		},
		projectManageWidgetOpenHandler:function(type){
			if(type!=this.projectType){
				this.destroyWidget();
			}
		},

		listenerMapLandClickHandler:function(evt){
			if(evt.graphic&&evt.graphic.attributes!=null&&this.addOrEdit!="editstate"){
				var attrs = evt.graphic.attributes;
				var dz = "";
				if(attrs.hasOwnProperty('CSMC')||attrs.hasOwnProperty('CS')){
					var cs = attrs.hasOwnProperty('CSMC')?attrs['CSMC']:(attrs.hasOwnProperty('CS')?attrs['CS']:"");
					dojo.query(".WYTZProjectManageWidget input[id='CS']")[0].value = cs;    
					dz += (cs==null?"":cs);
				}
				if(attrs.hasOwnProperty('FQMC')||attrs.hasOwnProperty('QJ')){
					var fq = attrs.hasOwnProperty('FQMC')?attrs['FQMC']:(attrs.hasOwnProperty('QJ')?attrs['QJ']:"");
					dojo.query(".WYTZProjectManageWidget input[id='QJ']")[0].value = fq;    
					dz += (fq==null?"":fq);
				}
				if(attrs.hasOwnProperty('ZJMC')||attrs.hasOwnProperty('ZJ')){
					var zj = attrs.hasOwnProperty('ZJMC')?attrs['ZJMC']:(attrs.hasOwnProperty('ZJ')?attrs['ZJ']:"");
					dojo.query(".WYTZProjectManageWidget input[id='ZJ']")[0].value = zj; 
					dz += (zj==null?"":zj);
				}
				if(dojo.query(".WYTZProjectManageWidget input[id='DZ']")){
					dojo.query(".WYTZProjectManageWidget input[id='DZ']")[0].value = dz; 
				}else if(dojo.query(".WYTZProjectManageWidget input[id='JTDZ']") ){
					dojo.query(".WYTZProjectManageWidget input[id='JTDZ']")[0].value = dz; 
				}else if(dojo.query(".WYTZProjectManageWidget input[id='XMDZ']") ){
					dojo.query(".WYTZProjectManageWidget input[id='XMDZ']")[0].value = dz; 
				}
				if(attrs.hasOwnProperty('BZ2')){
					dojo.query(".WYTZProjectManageWidget input[id='DKBM']")[0].value = attrs.hasOwnProperty('BZ2')?attrs['BZ2']:"";     
				}
			}else{
				return;
			}
		},
		editProjectInfo:function(){
			this.setTextType("resavestate");
		},
		beginDrawPoint:function(){
			debugger;
			if(this.drawtool){
				this.drawtool.activate(esri.toolbars.Draw.POINT);
				this.handles.push(on(this.drawtool, "draw-end",lang.hitch(this,this.addFeatureToMap)));
			}
		},
		addFeatureToMap:function(evt){
			if(this.drawtool){
				this.drawtool.deactivate();
			}

			var POISymbol = new PictureMarkerSymbol(require.toUrl("../WYTZProjectManageWidget/images/newproject.png"),22,24);
			POISymbol.setOffset(11, 12);
			var drawGraphic = new Graphic(evt.geometry, POISymbol);
			this.currentDrawGraphic = drawGraphic;
			this.map.graphics.clear();
			this.map.graphics.add(drawGraphic);
			this.map.setInfoWindowOnClick(true);
		},
		setTextType:function(addOrEdit){
			debugger;
			this.addOrEdit = addOrEdit;
			dojo.forEach(this.addbuttons,dojo.hitch(this,function(item){
				dojo.toggleClass(item,"colshowstate",addOrEdit!="addstate");
			}));
			dojo.forEach(this.editbuttons,dojo.hitch(this,function(item){

				dojo.toggleClass(item,"colshowstate",addOrEdit!="editstate");
			}));
			dojo.forEach(this.resavebuttons,dojo.hitch(this,function(item){

				if(dojo.hasClass(item,"resavestate")&&!dojo.hasClass(item,"editstate")||addOrEdit=="resavestate"){
					dojo.toggleClass(item,"colshowstate",addOrEdit!="resavestate");
				}

			}));
			var inputs = dojo.query(".WYTZProjectManageWidget .projectattr");
			dojo.forEach(inputs,dojo.hitch(this,function(item){
				dojo.toggleClass(item,"inputallowedit",addOrEdit=="editstate");
				dojo.toggleClass(item,"projectinfoinput",addOrEdit!="editstate");
				item.disabled = (addOrEdit=="editstate");
				if(addOrEdit=="addstate"){
					debugger;
					if(item.id!="USERNAME"&&item.id!="DQGS"&&item.id!="GS"&&item.id!="CSGSMC"&&item.id!="TZSYB"&&item.id!="TZZ"){
						item.value = "";
					}
					if(item.tagName.toLowerCase()=="select"){
						item.selectedIndex = 0;
					}
				}
			}));

			if(addOrEdit&&this.drawtool==null){
				this.drawtool = new Draw(this.map);//this.map);//使用toolbar上的绘图工具
			}
			if(dojo.byId("DKMC")||dojo.byId("XMMC")){
				this.projectName.innerText = dojo.byId("DKMC")?dojo.trim(dojo.byId("DKMC").value):(dojo.byId("XMMC")?dojo.trim(dojo.byId("XMMC").value):"");
			}
			if(addOrEdit!="addstate"){
				dojo.query(".projectinfotabledatarows").style("max-height", document.body.clientHeight-200+"px");
			}else{
				dojo.query(".projectinfotabledatarows").style("max-height", document.body.clientHeight-168+"px");
			}
		},
		windowResizeHandler:function(){
			//根据浏览器高度设置表格高度，避免双滚动条出现
			dojo.query(".projectinfotabledatarows").style("max-height", document.body.clientHeight-200+"px");
			dojo.query(".rightWidgetRoot .dijitContentPane").style("width", "100%");
			dojo.query(".rightWidgetRoot .dijitContentPane").style("height", "100%");
		},
		addLandsFeatureLayer:function (){
			this.LandFeatureLayer=new FeatureLayer(this.flyurl==null?(mapinfoTemplate[this.projectType].layerurl):this.flyurl);//"http://oracle-pc:6080/arcgis/rest/services/SDDCGIS/TZGK/FeatureServer/2");

			if(this.feaSet){
				this.createProjectDetailInfoTable(this.feaSet);
			}else{
				var queryTask = new QueryTask(mapinfoTemplate[this.projectType].maplayerinfo.url+"/"+mapinfoTemplate[this.projectType].maplayerinfo.sublyidx);//"http://oracle-pc:6080/arcgis/rest/services/SDDCGIS/TZGK/MapServer/2");
				var query = new Query();

				query.text = "objectid<0";
				query.outFields = ["*"]; 
				query.returnGeometry = false; 
				queryTask.execute(query, lang.hitch(this,this.createProjectDetailInfoTable)); 
			}
		},
		createProjectDetailInfoTable:function(result){
			if(result.fields){
				var fieldInfos = result.fields;
				if(fieldInfos&&fieldInfos.length>0){
					this.layerFieldsInfo = fieldInfos;
					var table = dojo.query("#projectinfo").empty();
					var html="";
					for(var i=0;i<fieldInfos.length;i++){
						var alias = fieldInfos[i].alias;
						var name = fieldInfos[i].name;
						var type = fieldInfos[i].type;
						if(name!="OBJECTID"){
							var tvalue = "";
							if(result.features.attributes){
								tvalue = result.features.attributes[name]==null?"":result.features.attributes[name];
							}
							html+="<tr class='datarow' ><td style='width:45%;'>"+alias+" </td><td style='width:55%;'>";
							switch(type){

							case "esriFieldTypeDate":
								var valproperty = "";
								if(DataFormate(tvalue).indexOf("-")!=-1){
									valproperty = "value='"+DataFormate(tvalue)+"'";
								}
								html +="<input id='"+name+"' class='projectattr dateinput projectinfoinput' placeholder='请选择日期' "+valproperty+" onFocus='WdatePicker({startDate:\"%y-%M-01\",dateFmt:\"yyyy-MM-dd\",alwaysUseStartDate:true})'>" +
								"</input>";
								break;
							default:

								if(name!="XMJD"&&name!="XMSX"&&name!="TZFS"&&name!="TGXX"&&name!="KGXX"&&name!="XMLX"){
									if(tvalue==""||tvalue==null){
										if(name=="USERNAME"){
											tvalue = ioc.map.userInfoData.DISPLAYNAME;
										}else if(name=="DQGS"||name=="GS"||name=="CSGSMC"){
											tvalue = ioc.map.userInfoData.COMPANYNAME;
										}else if(name=="TZSYB"){
											tvalue = ioc.map.userInfoData.BUSINAME;
										}else if(name=="TZZ"){
											tvalue = ioc.map.userInfoData.DEVNAME;
										}
									}
									html +="<input id='"+name+"' class='projectattr projectinfoinput' type='text' value='"+tvalue+"'></input>";
								}else{
									html += "<select id='"+name+"' class='projectattr projectinfoinput'>";
									var options = TZGKfieldSelectOptions[name];
									for(var s=0;s<options.length;s++){
										var isSelect = "";
										if(options[s].value==tvalue){
											isSelect = " selected='selected'";
										}
										html += "<option "+isSelect+" value='"+options[s].value+"'>"+options[s].text+"</option>";
									}
									html += "</select>";
								}
							}
							html+="</td></tr>";

						}
					}
					html=html.replace(/undefined/g,'');
					table.addContent(html);
				}
			}

		},
		closeDialog:function(){
			this.inherited("closeDialog",arguments);
			this.rightTab.expandBtn.click();
			this.destroyWidget();
		},
		destroyWidget:function(){
			dojo.forEach(this.handles, function(handle, i){
				handle.remove();//移除监听
			});
			this.destroy();
		},

		createLandBtnClickHandler:function(){
			this.saveLandGeometryToDB("add");
		},
		resaveLandBtnClickHandler:function(){
			this.saveLandGeometryToDB("update");
		},
		deleteLandBtnClickHandler:function(){
			this.saveLandGeometryToDB("delete");
		},
		saveLandGeometryToDB:function(editType){
			this.executeEditType = editType;
			if(this.layerFieldsInfo){
				if(this.currentDrawGraphic==null){
					layer.msg("请先在地图上取点!",{icon: 2,time: 3000});
					return;
				}
				var attributes = {};

				for(var i=0;i<this.layerFieldsInfo.length;i++){
					var fieldInfo = this.layerFieldsInfo[i];
					var name = fieldInfo.name;
					var dom = dojo.byId(name);
					if(dom){
						if(dom instanceof HTMLElement){
							var tagName = dom.tagName.toLowerCase();
							var value = "";
							if(tagName == "input"){
								if(dom.type == "text"){
									value = dojo.trim(dom.value) ? dojo.trim(dom.value) : null;
									if(name=="USERNAME"){
										value = ioc.map.userInfoData.USERNAME;
									}
								}
								else if(dom.type == "checkbox"){
									value = dom.checked ? "1" : "0";
								}
							}
							else if(tagName == "select"){
								value = dom.value;
							}
							attributes[name] = value;
						}
					}
				}
				var applyedits = {"add":null,"update":null,"delete":null};
				if(editType!="add"){
					attributes["OBJECTID"] = this.objectId;
				}

				this.currentDrawGraphic.attributes = attributes;
				applyedits[editType] = [this.currentDrawGraphic];
				var self=this;
				this.LandFeatureLayer.applyEdits(applyedits["add"],applyedits["update"],applyedits["delete"],
						function(evt){
					layer.close(index) ;
					if(evt.length>0){
						self.objectId = evt[0].objectId;
					}
					if(self.executeEditType=="delete"){
						self.setTextType("addstate");
					}else{
						self.setTextType("editstate");
					}

					layer.msg("保存成功!",{icon: 1,time: 3000});
				},
				function(evt){
					layer.close(index) ;
					layer.msg("保存失败!",{icon: 2,time: 3000});
				}
				);
				var index = layer.load(1);
			}
		},

	});

});

